<template>
    <div class="personal-info-container">
        <el-card>
            <template #header>
                <div>个人信息</div>
                <el-button type="primary" size="small" @click="handleEdit">编辑</el-button>
            </template>

            <el-descriptions :column="1" border>
                <el-descriptions-item label="真实姓名">
                    <el-tag>{{ userStore.userinfo?.real_name }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="用户名">
                    {{ userStore.userinfo?.username }}
                </el-descriptions-item>
                <el-descriptions-item label="手机号码">
                    {{ userStore.userinfo?.phone }}
                </el-descriptions-item>
                <el-descriptions-item label="邮箱账号">
                    {{ userStore.userinfo?.email }}
                </el-descriptions-item>
                <el-descriptions-item label="是否绑定邮箱">
                    <el-tag :type="userStore.userinfo?.email ? 'success' : 'danger'">
                        {{ userStore.userinfo?.email ? '已绑定' : '未绑定' }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="是否绑定微信">
                    <el-tag :type="userStore.wechat_bind ? 'success' : 'danger'">
                        {{ userStore.wechat_bind ? '已绑定' : '未绑定' }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="注册时间">
                    {{ formatDate(userStore.userinfo?.created_at) }}
                </el-descriptions-item>
                <el-descriptions-item label="上次更新时间">
                    {{ formatDate(userStore.userinfo?.updated_at) }}
                </el-descriptions-item>
            </el-descriptions>
        </el-card>

        <!-- 编辑个人信息对话框 -->
        <el-dialog v-model="dialogVisible" title="编辑个人信息" width="500px">
            <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
                <el-form-item label="真实姓名" prop="real_name">
                    <el-input v-model="form.real_name" />
                </el-form-item>
                <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="form.phone" />
                </el-form-item>
                <el-form-item label="邮箱账号" prop="email">
                    <el-input v-model="form.email" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useUserStore } from '@/stores/userinfo';
import { updateUserApi } from '@/api/user';

const userStore = useUserStore();
const dialogVisible = ref(false);
const formRef = ref(null);

// 表单数据
const form = reactive({
    real_name: '',
    phone: '',
    email: ''
});

// 表单验证规则
const rules = {
    real_name: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ]
};

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '未知';

    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 编辑按钮点击事件
const handleEdit = () => {
    if (userStore.userinfo) {
        form.real_name = userStore.userinfo.real_name || '';
        form.phone = userStore.userinfo.phone || '';
        form.email = userStore.userinfo.email || '';
    }
    dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return;

    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // 调用更新用户信息的API
                const updateData = {
                    id: userStore.userinfo.id,
                    real_name: form.real_name,
                    phone: form.phone,
                    email: form.email
                };

                const res = await updateUserApi(updateData);
                if (res.code === 200) {
                    // 更新成功后重新获取用户信息
                    await userStore.getUserInfo();
                    ElMessage.success('个人信息更新成功');
                    dialogVisible.value = false;
                } else {
                    throw new Error(res.message || '更新失败');
                }
            } catch (error) {
                console.error('更新个人信息失败', error);
                ElMessage.error(`更新个人信息失败：${error.message || '请稍后重试'}`);
            }
        } else {
            ElMessage.warning('请正确填写所有必填字段');
            return false;
        }
    });
};

// 组件挂载时获取用户信息
onMounted(async () => {
    if (!userStore.userinfo) {
        try {
            await userStore.getUserInfo();
        } catch (error) {
            console.error('获取用户信息失败', error);
            ElMessage.error('获取用户信息失败，请刷新页面重试');
        }
    }
});
</script>

<style scoped>
.personal-info-container {
    max-width: 900px;
    margin: var(--gap-normal) auto;
}
</style>